import React, { createContext, useEffect, useReducer, useState } from "react";
import { Alert } from "react-native";
import AsyncStorage from "@react-native-async-storage/async-storage";
import query from "../../api/query";
import { fileWeb } from "../../api/query";
import axios from "axios";

const ArticleContext = createContext();

const dataReducer = (state, action) => {
  switch (action.type) {
    case "fetch_init":
      return action.payload;
    case "add_article":
      return [...state, action.payload];
    case "edit_article": //传入整个文章对象
      return state.map((item) => {
        return item._id === action.payload._id ? action.payload : item;
      });
    case "delete_article": //传入文章_id
      return state.filter((item) => item._id !== action.payload);
    case "set_catagory": //传入修改后的文章列表
      return action.payload;
    // return state.map((item) => {
    //   if (
    //     item.type === action.payload.type &&
    //     item._id !== action.payload._id
    //   ) {
    //     item.type = 0;
    //   }
    //   if (item._id === action.payload._id) {
    //     item.type = action.payload.type;
    //   }
    //   return item;
    // });
  }
};

export const ArticleProvider = ({ children }) => {
  const [ArticleList, dispatch] = useReducer(dataReducer, []);
  const [isArticleLoading, setIsArticleLoading] = useState(false);
  const [isArticleError, setIsArticleError] = useState(false);

  useEffect(() => {
    const fetchData = async () => {
      setIsArticleLoading(true);
      setIsArticleError(false);
      try {
        const token = await AsyncStorage.getItem("token");
        const result = await query.get("/article", {
          headers: { Authorization: token },
        });
        dispatch({ type: "fetch_init", payload: result.data.data });
      } catch (err) {
        setIsArticleError(true);
        console.log("初始化文章出错", err);
      }
      setIsArticleLoading(false);
    };
    fetchData();
  }, []);

  const addArtical = async (article, callback) => {
    try {
      setIsArticleLoading(true);
      let formData = new FormData();
      if (article.imageList.length !== 0) {
        article.imageList.forEach((item) => {
          formData.append("files", {
            name: item.uri.split("/").pop(),
            uri: item.uri,
            type: "image/" + item.uri.split(".").pop(),
          });
        });
        //先处理图片
        let res = await fetch(fileWeb + "/upload/multi", {
          method: "post",
          headers: {
            "Content-Type": "multipart/form-data",
          },
          body: formData,
        });
        let response = await res.json();
        article.imageList = response.message;
        // console.log("------图片", response.message);
        //将content里的图片置换为网络图片
        let i = 0;
        const newContents = article.contents.map((item) => {
          if (item.type === 2) {
            item.content = response.message[i];
            i++;
          }
          return item;
        });
        article.contents = newContents;
      }
      //新增文章
      const token = await AsyncStorage.getItem("token");
      const result = await query.post("/article", article, {
        headers: { Authorization: token },
      });

      // console.log("返回结果---", result.data.data);

      dispatch({ type: "add_article", payload: result.data.data });
      Alert.alert("", "添加文章成功", [
        {
          text: "确定",
          onPress: () => callback(),
        },
      ]);
    } catch (err) {
      console.log("添加文章失败", err);
      Alert.alert("", "添加文章失败");
    }
    setIsArticleLoading(false);
  };

  const editArticle = async (
    article,
    originImages,
    deleteImages,
    newImages,
    callback
  ) => {
    try {
      setIsArticleLoading(true);
      let formData = new FormData();
      //需新增图片
      newImages.forEach((item) => {
        formData.append("files", {
          name: item.uri.split("/").pop(),
          uri: item.uri,
          type: "image/" + item.uri.split(".").pop(),
        });
      });
      //需删除图片
      deleteImages.forEach((item) => {
        formData.append("idGroup[]", item._id);
      });

      //需保留图片
      originImages.forEach((item) => {
        formData.append("origin[]", item._id);
      });

      // console.log("formdata", formData);

      let res = await fetch(fileWeb + "/upload/multi", {
        method: "patch",
        headers: {
          "Content-Type": "multipart/form-data",
        },
        body: formData,
      });
      let response = await res.json(); // if you do not use the await,you are logging the promise before it resolves
      // console.log("返回来的数据~", response.message);

      article.imageList = response.message;
      let i = 0;
      const newContents = article.contents.map((item) => {
        if (item.type === 2) {
          item.content = response.message[i];
          i++;
        }
        return item;
      });
      article.contents = newContents;

      const token = await AsyncStorage.getItem("token");
      const result = await query.patch("/article/" + article._id, article, {
        headers: { Authorization: token },
      });

      dispatch({ type: "edit_article", payload: result.data.data });
      Alert.alert("", "文章修改成功", [
        {
          text: "确定",
          onPress: () => callback(result.data.data),
        },
      ]);
    } catch (err) {
      console.log("编辑文章出错", err);
      Alert.alert("", "修改文章失败");
    }
    setIsArticleLoading(false);
  };

  const deleteArticle = async (article) => {
    try {
      setIsArticleLoading(true);
      let idGroup = article.imageList.map((item) => {
        return item._id;
      });
      await axios.delete(fileWeb + "/upload/multi", { data: idGroup });
      const token = await AsyncStorage.getItem("token");
      await query.delete("/article/" + article._id, {
        headers: { Authorization: token },
      });
      dispatch({ type: "delete_article", payload: article._id });
      Alert.alert("", "文章删除成功", [
        {
          text: "确定",
        },
      ]);
    } catch (err) {
      console.log("删除文章出错", err);
      Alert.alert("", "删除文章失败");
    }
    setIsArticleLoading(false);
  };

  const setCatagory = async (_id, type) => {
    let option = { _id: _id, type: type };
    try {
      setIsArticleLoading(true);
      const token = await AsyncStorage.getItem("token");
      const result = await query.post("/article/publish", option, {
        headers: { Authorization: token },
      });
      dispatch({ type: "set_catagory", payload: result.data.data });
      Alert.alert("", "文章发布成功", [
        {
          text: "确定",
        },
      ]);
    } catch (err) {
      console.log("文章发布失败", err);
      Alert.alert("", "文章发布失败");
    }
    setIsArticleLoading(false);
  };

  return (
    <ArticleContext.Provider
      value={{
        articleList: ArticleList,
        addArtical,
        setCatagory,
        editArticle,
        deleteArticle,
        isArticleLoading,
      }}
    >
      {children}
    </ArticleContext.Provider>
  );
};

export default ArticleContext;
